<?php


namespace app\controller\api;


use app\BaseController;
use app\common\exception\ApiException;
use app\common\RedisKey;
use app\model\article\ExamRuleModel;
use app\model\article\NoticeModel;
use app\model\topic\TopicModel;
use app\model\topic\UserTopicExerciseRecordModel;
use app\model\topic\UserTopicErrorModel;
use app\model\topic\UserTopicRecordModel;
use app\model\video\VideoChapterModel;
use app\model\video\VideoCourseModel;
use app\model\video\VideoNodeModel;
use think\facade\Cache;

class TopicController extends BaseController
{
    /**
     * 驾考
     * @return \think\response\Json
     */
    public function index()
    {
        try {
            $userId = $this->request->middleware('userId');
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');

            $result['max_score'] = UserTopicRecordModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->max('score');
            $result['avg_score'] = UserTopicRecordModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->avg('score');
            $total = UserTopicRecordModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->count();
            $pass = UserTopicRecordModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->where('score', '>=', 90)
                ->count();
            $result['pass_ratio'] = $total > 0 ? intval($pass / $total * 100) : 0;

            // 顺序练习数量
            $result['total'] = $total;
            $result['exercise_num'] = TopicModel::where('type', $type)
                ->where('subject', $subject)
                ->count();
            $result['exercise_max_topic_id'] = UserTopicExerciseRecordModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->max('topic_id');
            // 错题数量
            $result['error_num'] = UserTopicErrorModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->where('status', 0)
                ->count();
            // 收藏数量
            $result['collect_num'] = UserTopicErrorModel::where('type', $type)
                ->where('subject', $subject)
                ->where('user_id', $userId)
                ->where('status', 1)
                ->count();

            // 首页视频难点
            $courseList = VideoCourseModel::with('node')->order('sort', 'asc')->limit(3)->select();
            $redis = Cache::store('redis')->handler();
            $key = sprintf(RedisKey::USER_STUDY_COURSE, $userId);
            foreach ($courseList as &$value) {
                $value['is_study'] = $redis->SISMEMBER($key, $value['id']);
            }
            $result['course_list'] = $courseList;
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 全部考题
     * @return \think\response\Json
     */
    public function getTopicList()
    {
        try {
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');
            $topicId = $this->request->param('topic_id', 0, 'int');
            $page = $this->request->param('page', 1, 'int');
            $limit = $this->request->param('limit', 100, 'int');
            // 获取最小的题目ID
            $list = TopicModel::where('type', $type)
                ->where('subject', $subject)
                ->where('id', '>', $topicId)
                ->order('id', 'asc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 全部错题
     * @return \think\response\Json
     */
    public function getErrorTopicList()
    {
        try {
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');
            $topicId = $this->request->param('topic_id', 0, 'int');

            $idArr = UserTopicErrorModel::where('type', $type)
                ->where('subject', $subject)
                ->where('status', 0)
                ->order('id', 'asc')
                ->column('topic_id');
            $list = TopicModel::whereIn('id', $idArr)
                ->where('id', '>', $topicId)
                ->order('id', 'asc')
                ->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 全部收藏题
     * @return \think\response\Json
     */
    public function getCollectTopicList()
    {
        try {
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');
            $topicId = $this->request->param('topic_id', 0, 'int');

            $idArr = UserTopicErrorModel::where('type', $type)
                ->where('subject', $subject)
                ->where('status', 1)
                ->column('topic_id');

            $list = TopicModel::whereIn('id', $idArr)
                ->where('id', '>', $topicId)
                ->order('id', 'asc')
                ->select();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 全部收藏题号
     * @return \think\response\Json
     */
    public function getCollectTopicIdArr()
    {
        try {
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');

            $idArr = UserTopicErrorModel::where('type', $type)
                ->where('subject', $subject)
                ->where('status', 1)
                ->column('topic_id');
            return $this->success($idArr);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 模拟考试
     * @return \think\response\Json
     */
    public function getPracticeTestList()
    {
        try {
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');
            $limit = $subject == 1 ? 100 : 50;
            $list = TopicModel::where('type', $type)
                ->where('subject', $subject)
                ->limit($limit)
                ->orderRaw("RAND()")
                ->select();
            $list = array_sort($list, 'id', 'asc');
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 提交考试
     * @return \think\response\Json
     */
    public function submitTopic()
    {
        try {
            $userId = $this->request->middleware('userId');
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');
            $score = $this->request->param('score', 0, 'int');
            $correct = $this->request->param('correct', 0, 'int');
            $error = $this->request->param('error', 0, 'int');
            $errorTopicIds = $this->request->param('error_topic_ids', '', 'trim');

            $userTopicRecordModel = new UserTopicRecordModel();
            $userTopicRecordModel->user_id = $userId;
            $userTopicRecordModel->type = $type;
            $userTopicRecordModel->subject = $subject;
            $userTopicRecordModel->score = $subject == 1 ? $correct : $correct * 2;
            $userTopicRecordModel->correct = $correct;
            $userTopicRecordModel->error = $error;
            $userTopicRecordModel->save();

            $errorTopicIdArr = explode(',', $errorTopicIds);
            $dataAll = [];
            if (is_array($errorTopicIdArr)) {
                foreach ($errorTopicIdArr as $k => $v) {
                    $topicInfo = TopicModel::find($v);
                    if (!$topicInfo) {
                        continue;
                    }
                    $dataAll[$k] = [
                        'user_id' => $userId,
                        'type' => $topicInfo['type'],
                        'subject' => $topicInfo['subject'],
                        'topic_id' => $v,
                    ];
                }
                $userTopicErrorModel = new UserTopicErrorModel();
                $userTopicErrorModel->saveAll($dataAll);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 收藏
     * @return \think\response\Json
     */
    public function collect()
    {
        try {
            $userId = $this->request->middleware('userId');

            $topicId = $this->request->param('topic_id', 0, 'int');
            $topicInfo = TopicModel::find($topicId);
            if (!$topicInfo) {
                throw new ApiException('数据不存在');
            }
            $info = UserTopicErrorModel::where('user_id', $userId)
                ->where('topic_id', $topicId)
                ->where('status', 1)
                ->withTrashed()
                ->find();
            if (!$info) {
                $userTopicErrorModel = new UserTopicErrorModel();
                $userTopicErrorModel->user_id = $userId;
                $userTopicErrorModel->type = $topicInfo['type'];
                $userTopicErrorModel->subject = $topicInfo['subject'];
                $userTopicErrorModel->topic_id = $topicId;
                $userTopicErrorModel->status = 1;
                $userTopicErrorModel->save();
            } else {
                if ($info['delete_time'] == 0) {
                    $info->delete();
                } else {
                    $info->restore();
                }
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 视频列表
     * @return \think\response\Json
     */
    public function getVideoList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $chapterList = VideoChapterModel::select();
            $redis = Cache::store('redis')->handler();
            $rediskey = sprintf(RedisKey::USER_STUDY_COURSE, $userId);

            foreach ($chapterList as $key => $value) {
                $nodeList = VideoNodeModel::where('chapter_id', $value['id'])->select();
                $chapterList[$key]['node_list'] = $nodeList;
                foreach ($nodeList as $k => $v) {
                    $courseList = VideoCourseModel::where('node_id', $v['id'])->select();
                    foreach ($courseList as $it => $item) {
                        $courseList[$it]['is_study'] = $redis->SISMEMBER($rediskey, $item['id']);
                    }
                    $nodeList[$k]['course_list'] = $courseList;
                }
            }
            return $this->success($chapterList);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 学习视频
     * @return \think\response\Json
     */
    public function studyVideo()
    {
        try {
            $userId = $this->request->middleware('userId');
            $courseId = $this->request->param('course_id', 0, 'int');
            $courseInfo = VideoCourseModel::find($courseId);
            if (!$courseInfo) {
                throw new ApiException('课程不存在');
            }
            $redis = Cache::store('redis')->handler();
            $rediskey = sprintf(RedisKey::USER_STUDY_COURSE, $userId);
            $redis->SADD($rediskey, $courseId);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }


    /**
     * 历史成绩
     * @return \think\response\Json
     */
    public function getHistoryScore()
    {
        try {
            $userId = $this->request->middleware('userId');
            $type = $this->request->param('type', 'C1,C2,C3', 'trim');
            $subject = $this->request->param('subject', 1, 'int');
            $list = UserTopicRecordModel::where('user_id', $userId)
                ->where('type', $type)
                ->where('subject', $subject)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}